package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.service.MemberService;
import com.xrit.sunnyday.service.ReportService;
import com.xrit.sunnyday.service.SetmealService;
import com.xrit.sunnyday.utils.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setMealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员数量
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        List<String> months=new ArrayList<String>();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR,-1);
        for(int i=0;i<12;i++){
            try{
                // 每次增加一个月就
                calendar.add(Calendar.MONTH, 1);
                // 过去的日期, 设置好的日期
                Date date = calendar.getTime();
                // 转换成我们数据库可以使用的'yyyy-MM-dd'字符串
                String dateString = DateUtils.parseDate2String(date);
                //添加组拼好的过去12个月的月份到List集合
                months.add(dateString);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        List<Integer> memberCount =memberService.getMemberReport(months);
        // 放入map
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("months",months);
        resultMap.put("memberCount",memberCount);

        // 再返回给前端
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,resultMap);
    }

    /**
     * 套餐占比
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //调用服务查询套餐预约占比,只需要查出它，它包含了前端页面需要的套餐名称集合
        List<Map<String,Object>> setmealCount = setMealService.findSetmealCount();

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,setmealCount);
    }


    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String, Object> businessReport = reportService.getBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReport);
    }

    @GetMapping("exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res){
        Map<String,Object> reportData=reportService.getBusinessReportData();
        String template=req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");

        try(
                FileInputStream file=new FileInputStream(template);
                OutputStream ot=res.getOutputStream();
                Workbook wb=new XSSFWorkbook(file))
        {
            XSSFSheet sht= (XSSFSheet) wb.getSheetAt(0);
            sht.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());
            sht.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            sht.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            sht.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            sht.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));
            sht.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            sht.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            sht.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            sht.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            sht.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            sht.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            List<Map<String,Object>> hotSetmeal = (List<Map<String,Object>> )reportData.get("hotSetmeal");
            int row=12;
            for (Map<String, Object> stringObjectMap : hotSetmeal) {
                sht.getRow(row).getCell(4).setCellValue((String)stringObjectMap.get("name"));
                sht.getRow(row).getCell(5).setCellValue((Long)stringObjectMap.get("setmeal_count"));
                BigDecimal proportion = (BigDecimal) stringObjectMap.get("proportion");
                sht.getRow(row).getCell(6).setCellValue(proportion.doubleValue());
                sht.getRow(row).getCell(7).setCellValue((String)stringObjectMap.get("remark"));
                row++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");

            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            wb.write(ot);
            ot.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
